<template>
  <div>
    <el-upload :action="`${$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/smis`"
      :headers="{token: $cookie.get('token')}" :accept="accept" :limit="limit" list-type='picture-card'
      :before-upload="checkMeasure" :on-success="(response, file, fileList) => {
        // filePath = (file.response && file.response.url) || file.url
        filePath = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
				$emit('onNameChange', file.name)
      }" :on-progress="onProgress" :on-exceed="(files, fileList)=> {
        $message.warning(`只允许上传选择 ${limit} 个文件`)
      }" :on-remove="(file, fileList) => {
        // $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
        //  $message.success(data.msg)
        // })
        // filePath = ''
        filePath = fileList.map(item => item.url).join('|')
      }" :file-list="files">
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <div v-if="!file.response && file.url.startsWith('blob:')" style="height: auto; text-align: center;"
          class="el-upload-list__item-thumbnail uni-center-xy">{{percent === '100%' ? '处理中...': '上传中'+percent+'...'}} </div>
        <video v-else-if="file.name.endsWith('.mp4')" class="el-upload-list__item-thumbnail uni-center-xy"
          :src="file.url">
          您的浏览器不支持 video 标签。
        </video>
        <img v-else-if="file.name.endsWith('.png') || file.name.endsWith('.jpg') || file.name.endsWith('.jpeg')"
          style="height: auto;" class="el-upload-list__item-thumbnail uni-center-xy" :src="file.url" alt="file.name">
        <div v-else style="height: auto; line-height: 1.8; background-color: #CCCCCC; text-align: center;"
          class="el-upload-list__item-thumbnail uni-center-xy" alt="file.name">
          {{file.name}}
        </div>
        <img src="../../assets/img/video.png" class="uni-center-xy" style="width: 40px; z-index: 0;"
          v-if="!(!file.response && file.url.startsWith('blob:')) && file.name.endsWith('.mp4')">
        <span class="el-upload-list__item-actions">
          <!-- <span class="el-upload-list__item-preview"  @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span> -->
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <!-- <el-button size="small" type="primary">点击上传</el-button> -->
      <div slot="tip" class="el-upload__tip">只能上传{{accept}}格式文件<span
          v-if="fileType === '2'">，图片尺寸要求：{{width}}*{{height}}</span></div>
    </el-upload>
    <!-- vueCropper 剪裁图片实现-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" append-to-body>
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <vueCropper ref="cropper" :img="option.img" :outputSize="outputSize" :outputType="outputType"
            :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox"
            :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"  :autoCropHeight="option.autoCropHeight" :mode="option.mode" :fixed="option.fixed"
            :fixedNumber="option.fixedNumber" :centerBox="option.centerBox" :infoTrue="option.infoTrue"
            :fixedBox="option.fixedBox" :high="option.high" :enlarge="option.enlarge" @imgLoad="cropperLoad" ></vueCropper>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="finish" :loading="loading">裁剪</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  // import VueCropper from 'vue-cropper'
  export default {
    name: "elUploadExt",
    data() {
      return {
        filePath: "",
        files: [],
        percent: '',
        dialogVisible: false,
        // 裁剪组件的基础配置option
        dialogTitle: '图片裁剪',
        option: {
          // img: '', // 裁剪图片的地址
          // outputSize: 1, // 裁剪生成图片的质量
          // outputType: 'png', // 裁剪生成图片的格式
          // full: true, // 是否输出原图比例的截图
          // info: true, // 图片大小信息
          // canScale: true, // 图片是否允许滚轮缩放
          // autoCrop: true, // 是否默认生成截图框
          // autoCropWidth: 500, // 默认生成截图框宽度
          // autoCropHeight: 450, // 默认生成截图框高度
          // canMove: true, // 上传图片是否可以移动
          // fixedBox: true, // 固定截图框大小 不允许改变
          // fixed: false, // 是否开启截图框宽高固定比例
          // canMoveBox: true, // 截图框能否拖动
          // original: false, // 上传图片按照原始比例渲染
          // centerBox: false, // 截图框是否被限制在图片里面
          // height: true,
          // infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
          // enlarge: 1, // 图片根据截图框输出比例倍数
          // mode: '100% auto', // 图片默认渲染方式
          // maxImgSize: 375 // 限制图片最大宽度和高度
          img: '', // 裁剪图片的地址
          info: true, // 裁剪框的大小信息
          // outputSize: 1, // 裁剪生成图片的质量
          // outputType: 'png', // 裁剪生成图片的格式
          canScale: true, // 图片是否允许滚轮缩放
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 300, // 默认生成截图框宽度
          autoCropHeight: 500, // 默认生成截图框高度
          fixedBox: true, // 固定截图框大小 不允许改变
          fixed: true, // 是否开启截图框宽高固定比例
          fixedNumber: [1, 1], // 截图框的宽高比例
          full: false, // 是否输出原图比例的截图
          canMoveBox: false, // 截图框能否拖动
          original: false, // 上传图片按照原始比例渲染
          centerBox: false, // 截图框是否被限制在图片里面
          high: false,
          mode: 'contain',
          // mode: '100% auto', // 图片默认渲染方式
          maxImgSize: 20000, // 限制图片最大宽度和高度
          enlarge: 1,
          infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        },
        // 防止重复提交
        loading: false,
				_name: ""
      };
    },
    props: {
      limit: {
        type: Number,
        default: 1
      },
      disabled: {
        type: Boolean,
        default: false
      },
      accept: {
        type: String,
        default: () => {
          return null
        }
      },
      fileType: {
        type: String,
        default: () => {
          return null
        }
      },
      width: {
        type: String,
        default: () => {
          return ''
        }
      },
      height: {
        type: String,
        default: () => {
          return ''
        }
      },
      outputSize: {
        // 裁剪生成图片的质量 0.0~1.0
        type: Number,
        default: 1
      },
      outputType: {
        type: String,
        default: 'png', // 裁剪生成图片的格式
      },
      allowScale: {
        // 是否允许同比例的
        type: Boolean,
        default: true
      },
      allowOtherSize: {
        // 是否允许其他尺寸
        type: Boolean,
        default: false
      },
      maxImageSize: {
        // 是否允许其他尺寸
        type: Number,
        default: 3 * 1024 * 1024
      },
      value: {
        type: String,
        default: () => {
          return null
        }
      },
			name: {
				type: String,
				default: () => {
				  return ""
				}
			}
    },
    // components: {
    //   VueCropper,
    // },
    computed: {
      // files: {
      //   get () {
      //     if (!this.filePath) {
      //       return []
      //     }
      //     var arr = []
      //     var list = this.filePath.split("|");
      //     list.forEach((path)=>{
      //       var obj= path.lastIndexOf("/")
      //       var fileName = path.substr(obj+1)
      //       arr.push({name: fileName, url: path})
      //     })
      //     return arr
      //   }
      // }
    },
    watch: {
      value(val) {
        if (this.filePath !== val) {
          this.filePath = val
          this.computedFiles(val)
        }
      },
      filePath(val) {
				var _val = val || '';
				var urls = this.myTrim(_val, '|')
        this.$emit('input', urls)
				this.$emit('onChange', urls)
      }
    },
    methods: {
      myTrim(str,char) {
        return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
      },
      computedFiles(val) {
        this.files = []
        if (val) {
          var list = val.split("|");
          list.forEach((path) => {
            var obj = path.lastIndexOf("/")
            var fileName = path.substr(obj + 1)
						if(this.name && this.name !== "") {
							fileName = this.name
						}
            this.files.push({
              name: fileName,
              url: path
            })
          })
        }
      },
      onProgress(event, file, fileList) {
        this.percent = Math.floor(event.percent)+"%"
      },
      cropperLoad(data){
        if(data === 'success') {
          var cropW = this.$refs.cropper.cropW
          var autoCropWidth = this.option.autoCropWidth
          this.option.enlarge = autoCropWidth*1.0/cropW
        }
      },
      // 点击裁剪，这一步是可以拿到处理后的地址
      finish() {
        // this.$refs.cropper.getCropData((data) => {
        //   let image = new Image()
        //   image.src = data
        //   image.onload = (e) => {
        //    console.log(image.width+','+image.height)
        //   }
        // })
        // return
        this.$refs.cropper.getCropBlob((data) => {
          //上传到服务器
          let file = new window.File([data], '123.png', {type: 'image/png'})
          this.loading = true
          var formData = new FormData()
          formData.append('file', file)
          this.$http({
            url: '/sys/file/webupload/upload?uploadPath=/smis',
            method: 'post',
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then(({data}) => {
            this.loading = false
            if (data && data.success) {
              this.dialogVisible = false
              if(this.filePath && this.filePath !== '') {
                this.filePath = this.filePath+'|'+data.url
              } else {
                this.filePath = data.url
              }
              console.log(data.name)
							this.$emit("onNameChange", data.name)
              this.computedFiles(this.filePath)
            }
            this.loading = false
          }).catch(err => {
            this.loading = false
          })
        })
      },
			_greater2G(file){
				if (file.size > 2 * 1024 * 1024 * 1024) {
					this.$message.warning(`文件大小不能超过2G`)
				  return true
				}
				return false
			},
      checkMeasure(file) {
        if (this.files.length >= this.limit) {
          this.$message.warning(`只允许上传选择 ${this.limit} 个文件`)
          return false
        }
        if (file && file.type && !file.type.startsWith("image")) {
          // 非图片的内容
					if(this._greater2G(file)) {
						return false
					}
          return true
        }
        if (file && file.type && file.type.startsWith("image/gif")) {
          // 非图片的内容
					if(this._greater2G(file)) {
						return false
					}
          return true
        }
        if (this.fileType !== '2') {
          // 如果不是图片，则不检测长宽
          return true
        }
        if (!this.width || this.width === '') {
          // 不检测宽度
          return true
        }
        if (!this.height || this.height === '') {
          // 不检测高度
          return true
        }
        if (!this.height || this.height === '') {
          // 不检测高度
          return true
        }
        if (file.size > this.maxImageSize) {
          if (this.maxImageSize < 1024 * 1024) {
            this.$message.warning('图片大小不能超过' + Math.floor(this.maxImageSize / 1024) + 'k')
          } else {
            this.$message.warning('图片大小不能超过' + (this.maxImageSize / (1024 * 1024)).toFixed(1) + 'M')
          }

          return false
        }

        var width = parseInt(this.width)
        var height = parseInt(this.height)
        var that = this
        const isSize = new Promise((resolve, reject) => {
          let _URL = window.URL || window.webkitURL
          let image = new Image()
          image.onload = (e) => {
            // console.log(e)
            if (that.allowScale && (image.width * 1.0 / image.height).toFixed(2) === (width * 1.0 / height).toFixed(2)) {
              resolve()
            } else if (!that.allowScale && image.width === width && image.height === height) {
              resolve()
            } else if (that.allowOtherSize) {
              that.$confirm('图片尺寸' + image.width + '*' + image.height + '，不符合要求的尺寸' + width + '*' + height +
                ', 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                resolve()
              }).catch(() => {
                reject()
              })
            } else {
              reject()
              that.dialogTitle = '图片尺寸' + image.width + '*' + image.height + '，不符合要求的尺寸' + width + '*' + height
              var reader = new FileReader();
              reader.onload = function(e) {
              	that.option.fixedNumber = [width, height]
                that.option.autoCropWidth = width // 默认生成截图框宽度
                that.option.autoCropHeight = height // 默认生成截图框高度
                that.option.img = e.target.result
                that.dialogVisible = true
              };
              reader.readAsDataURL(file);
              // that.$message.warning('图片尺寸' + image.width + '*' + image.height + '，不符合要求的尺寸' + width + '*' +
              //   height)
            }
          }
          image.src = _URL.createObjectURL(file)
        }).then(
          () => { // resolve
            return file;
          },
          () => { // 取消上传 reject
            return Promise.reject();
          }
        )
        return isSize
      },
      handleRemove(file) {
        this.files = this.files.filter((item) => {
          return item.uid !== file.uid
        })
        this.filePath = this.files.map(item => item.url).join('|')
      },
      handlePictureCardPreview(file) {
        // this.dialogImageUrl = file.url;
        // this.dialogVisible = true;
      },
      handleDownload(file) {
        console.log(file.url)
        window.location = file.url;
        // console.log(file);
      }
    }
  };
</script>
<style scoped="scoped">
  .cropper-content .cropper {
    width: 100%;
    height: 300px;
  }
</style>
